import cache from './cache';
import _ from 'lodash';
import UserPng from '@/assets/images/user.png';
import { getUserByIdApi, getUserByUserLoginNameApi } from '@/services/user';
import type { UserInfoProp } from '@/utils/organization';
import { getOrganizationInfo, organizationDB } from '@/utils/organization';
import defaultSettings from '@/constant/defaultSettings';
import { textBecomeImg } from './textToCanvas';
import { getImageById } from '@/utils/utils';

const { MAIN_CONFIG } = defaultSettings;
const { user, currentUser, userExtra }: any = cache;

const userMap = {};

export function setCurrentUser(user: any) {
  currentUser.set('default', user);
}
export function getCurrentUser() {
  return currentUser.get('default');
}

// indexDB缓存用户的任务
const userIndexDbTask = async (id: string, data: any) => {
  const has = await organizationDB.users.get({ id });
  if (!has && data) {
    organizationDB.addTableList(organizationDB.users, [data]);
  }
};

//设置用户缓存
export const setUser = ({
  id,
  data,
  userLoginName,
  initial = false,
}: {
  id?: string;
  userLoginName?: string;
  data: UserInfoProp;
  initial?: boolean;
}) => {
  id && user.set(id, data);
  userLoginName && userExtra.set(userLoginName, data);
  //indexDb增加用户
  if (!initial && data) {
    userIndexDbTask(data.id, data);
  }
};

// 内存缓存用户的任务
const userIdCacheTask = async (id: string) => {
  if (userMap[id]) {
    return new Promise((res) => {
      const interval = setInterval(() => {
        if (user.get(id)) {
          clearInterval(interval);
          res(user.get(id));
        }
      }, 40);
    });
  }
  userMap[id] = true;
  const userInfo = await getUserByIdApi({ id });
  setUser({ id, data: userInfo });
  return userInfo;
};

// 通过id获取用户信息防抖
const userIdCacheTaskDebounce = _.debounce(userIdCacheTask, 20);

/**
 *
 * 内存缓存用户的任务
 * @param {string} userLoginName
 */
const userLoginCacheTask = async (userLoginName: string) => {
  if (userMap[userLoginName]) {
    return new Promise((res) => {
      const interval = setInterval(() => {
        if (userExtra.get(userLoginName)) {
          clearInterval(interval);
          res(userExtra.get(userLoginName));
        }
      }, 40);
    });
  }
  userMap[userLoginName] = true;
  const userInfo = await getUserByUserLoginNameApi({ userLoginName });
  setUser({ userLoginName, data: userInfo });
  return userInfo;
};

// 通过名称获取用户缓存信息防抖
const userLoginCacheTaskDebounce = _.debounce(userLoginCacheTask, 20);

// 获取指定用户信息
export const getUserInfo = (id?: string, userLoginName?: string) => {
  const userInfo = id ? user.get(id) : userLoginName ? userExtra.get(userLoginName) : {};
  if (_.isEmpty(userInfo)) {
    id && userIdCacheTaskDebounce(id);
    userLoginName && userLoginCacheTaskDebounce(userLoginName);
  } else {
    if (userInfo.organizationId) {
      const organization = getOrganizationInfo(userInfo.organizationId);
      organization && (userInfo.orgName = _.get(organization, 'orgName'));
    }
  }
  return userInfo || {};
};

// 异步获取指定用户信息
export const getUserInfoAsync = async (id?: string, userLoginName?: string) => {
  let userInfo = id ? user.get(id) : userLoginName ? userExtra.get(userLoginName) : {};
  if (_.isEmpty(userInfo)) {
    if (id) {
      userInfo = await userIdCacheTask(id);
    } else if (userLoginName) {
      userInfo = await userLoginCacheTask(userLoginName);
    }
  }
  return userInfo || {};
};

// 获取用户图像
export const getAvatar = (userInfo: UserInfoProp) => {
  let avatarUrl = UserPng;
  if (!_.isEmpty(userInfo)) {
    const { userName } = userInfo;
    if (userName && userName.match(/^[\u4E00-\u9FA5]+$/)) {
      const base64 = textBecomeImg(userName.slice(userName.length - 2, userName.length), {
        fontSize: 32,
        fontColor: '#fff',
        alpha: 1,
        rotate: 0,
        padding: 0,
        background: '#0189FF',
      });
      avatarUrl = base64;
    }
    if (userInfo.pictureId) {
      avatarUrl = getImageById(userInfo.pictureId);
    }
  }
  return avatarUrl;
};

// 获取缓存的用户信息的指定字段
export const getUserField = ({
  id,
  field = 'userName',
  separator = ',',
}: {
  id: string | string[];
  field?: string;
  separator?: string;
}) => {
  if (!id || !id.length) return '';
  const mapIdToName = (_id: string) => {
    const userInfo = getUserInfo(_id);
    if (MAIN_CONFIG.userColumnShowLogin) {
      return userInfo[field] ? userInfo[field] + '-' + userInfo.userLoginName : '';
    } else {
      return userInfo[field] || '';
    }
  };
  if (Array.isArray(id)) {
    return id.map(mapIdToName).join(separator);
  }
  return mapIdToName(id);
};
